#include "data_proc.h"
#include "msgList.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <time.h>
#include <sys/time.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>




int flagDataProcRunning = 0;
pthread_t dataProc_ThreadHandle;

void *threadFunc_dataProc(void *arg)
{
    CRecvPool * recvPool = (CRecvPool *)arg;
	msg_recv * oneMsg = NULL;

    paramRecv recvParams; 
	
    //char devId[40] = "100";
	char buffOut[1024];
	int lenOut = 0;
	struct in_addr addr;
	char ipPort[64] = {0};
	char * pIp = NULL;
	while(flagDataProcRunning)
	{
	    oneMsg = recvPool->getOneMsg(1);
     
		if(oneMsg)
		{
		    //printf("getMsg success: len[%d],buff[%s],peerIp[%x:%d]\n",oneMsg->msgLen,oneMsg->buff,oneMsg->peerIp,oneMsg->peerPort);  

			memset(&recvParams,0,sizeof(paramRecv));
			if(oneMsg->buff[0] == UPDATE_IP_CODE)
			{
			    getQueryParam(oneMsg->buff + 1,oneMsg->msgLen-1, &recvParams);
	            printf("devId is:%s,time is %d\n",recvParams.devId,recvParams.timeRecv);
				addr.s_addr = oneMsg->peerIp;
	            pIp=inet_ntoa(addr);
				sprintf(ipPort,"%s:%d",pIp,oneMsg->peerPort);
				time_t t;
 	            time( &t);
				recvParams.timeRecv = t;
				//getQueryResult(recvParams.timeRecv,recvParams.devId,ipPort,buffOut,&lenOut);
				updateIp_MySql(recvParams.timeRecv,recvParams.devId,
				               oneMsg->peerIp,oneMsg->peerPort,oneMsg->fd);
				
				//strcpy(buffOut,"echo123");
                //recvPool->addOneMsg(strlen(buffOut),buffOut,oneMsg->peerIp,oneMsg->peerPort,oneMsg->fd,0);
			}
			else if(oneMsg->buff[0] == ACK_CODE)
			{
			    getQueryParam(oneMsg->buff + 1,oneMsg->msgLen-1, &recvParams);
				updateStatus_MySql(recvParams.devId, recvParams.snapshot);
			}
			else if(strncmp(oneMsg->buff,"fd",2)==0)
			{//php->udp->here
			    char * ptrTmp = oneMsg->buff;
			    ptrTmp+=3;
			    char * ptrBuff = strchr(oneMsg->buff,',');
			    ptrBuff++;

			    char strFd[16] = {0};
			    memset(strFd,0,16);
			    memcpy(strFd,ptrTmp,ptrBuff-ptrTmp);
			    int fd_send = atoi(strFd);
			    //printf("add to send msg list\n");
			    recvPool->addOneMsg(strlen(ptrBuff),ptrBuff,0,0,fd_send,0);
			}
			
			memset(oneMsg,0,sizeof(msg_recv));
		    free(oneMsg);
			oneMsg = NULL;
		}
		usleep(200);	    
	}

	return (void*)0;
}

void getQueryResult(int timeIn,char * devId,char * ipPort,char * buffOut, int * lenOut)
{
    char strTime[64];

	char queryStr[256];
	char fileName[256];
    int fd = -1;
	int readCount = 0;
	char buffRead[1024] = {0};
	int totalLen = 0;
	char strIp[64] = {0};
	
	
	sprintf(strTime,"time=%d",timeIn);

	sprintf(fileName,"/home/yt/socket/tmp/%d",timeIn);

    sprintf(queryStr,"curl 127.0.0.1/tp5/?%s\\&devId=%s\\&ip=%s > %s",strTime,devId,ipPort,fileName);

    //printf("curl string: %s\n",queryStr);
	system(queryStr);
	
	fd = open(fileName,O_RDONLY);

    if(fd==-1)
    {
       printf("open file [%s] failed\n",fileName);
	   return;
    }
	while(1)
	{
	   readCount = read(fd,buffRead,1024);
       if(readCount==0)
       {
           //printf("no data in file now\n");
           break;
       }
	   //printf("string from file :%s\n",buffRead);

	   memcpy(buffOut+totalLen,buffRead,readCount);
	   
	   totalLen += readCount;

	   memset(buffRead,0,1024);	   
	}

	close(fd);
	remove(fileName);
	*lenOut = totalLen;
	
}

void getQueryParam(char * buff, int buffLen, paramRecv * paramResult)
{
    char * ptrStr = buff;
    char * ptrTmp = NULL;
	int pos = 0;
	int flag = 1;
	int lenTemp = 0;
	char timeBuff[64];
	
    if(ptrStr==NULL)
    {
        return;
    }
    
//	while(flag)
	{
	   flag = 0;
	   ptrStr = strstr(buff,"devId");
	   if(ptrStr)
	   {
	       ptrStr+=6;//"devId=xxx"
		   ptrTmp = strchr(ptrStr,',');
		   if(ptrTmp)
		   {
		      lenTemp =  ptrTmp - ptrStr;
			  
		   }
		   else
		   {
		      lenTemp =  buff + buffLen - ptrStr; 
		   }
		   memcpy(paramResult->devId,ptrStr,lenTemp);
	       flag = 1;
	   }

	   ptrStr = strstr(buff,"time");
	   if(ptrStr)
	   {
                   char tempChr = 0;
		   ptrStr+=5;//"time=xxx"
                   ptrTmp = ptrStr;
                   tempChr = *ptrTmp;
                   while(  tempChr != ','
                        && tempChr != '\0'
                        && tempChr != '&'
                        )
                   {
                       ptrTmp++;
                       tempChr=*ptrTmp;                         
                   }
		   //ptrTmp = strchr(ptrStr,',');
		   //if(ptrTmp)
		   //{
		   //	  lenTemp =  ptrTmp - 1 - ptrStr;			  
		   //}
		   //else
		   //{
		  //	  lenTemp =  buff + buffLen - ptrStr; 
		   //}
                   lenTemp =  ptrTmp - ptrStr;
		   memset(timeBuff,0,64);
		   memcpy(timeBuff,ptrStr,lenTemp);
		   flag = 1;
		   paramResult->timeRecv = atoi(timeBuff);
	   }

	   ptrStr = strstr(buff,"snapshot");
	   if(ptrStr)
	   {
                   char tempChr = 0;
		           ptrStr+=9;//"time=xxx"
                   ptrTmp = ptrStr;
                   tempChr = *ptrTmp;
                   while(  tempChr != ','
                        && tempChr != '\0'
                        && tempChr != '&'
                        )
                   {
                       ptrTmp++;
                       tempChr=*ptrTmp;                         
                   }
		   //ptrTmp = strchr(ptrStr,',');
		   //if(ptrTmp)
		   //{
		   //	  lenTemp =  ptrTmp - 1 - ptrStr;			  
		   //}
		   //else
		   //{
		  //	  lenTemp =  buff + buffLen - ptrStr; 
		   //}
                   lenTemp =  ptrTmp - ptrStr;
		   memset(paramResult->snapshot,0,40);
		   memcpy(paramResult->snapshot,ptrStr,lenTemp);
		   flag = 1;
		   
	   }
	}
}


void getSendParam(char * buff, int buffLen, paramSend * paramResult)
{
    char * ptrStr = buff;
    char * ptrTmp = NULL;
	int pos = 0;
	int flag = 1;
	int lenTemp = 0;
	char timeBuff[64];
	char typeBuff[32];
    if(ptrStr==NULL)
    {
        return;
    }

	while(flag)
	{
	   flag = 0;  

	   ptrStr = strstr(ptrStr,"time");
	   if(ptrStr)
	   {
		   ptrStr+=5;//"time=xxx"
		   ptrTmp = strchr(ptrStr,',');
		   if(ptrTmp)
		   {
			  lenTemp =  ptrTmp - 1 - ptrStr;			  
		   }
		   else
		   {
			  lenTemp =  buff + buffLen -1 - ptrStr; 
		   }
		   memset(timeBuff,0,64);
		   memcpy(timeBuff,ptrStr,lenTemp);
		   flag = 1;
		   paramResult->timeRecv = atoi(timeBuff);
	   }

	   ptrStr = strstr(ptrStr,"type");
	   if(ptrStr)
	   {
		   ptrStr+=5;//"type=xxx"
		   ptrTmp = strchr(ptrStr,',');
		   if(ptrTmp)
		   {
			  lenTemp =  ptrTmp - 1 - ptrStr;			  
		   }
		   else
		   {
			  lenTemp =  buff + buffLen -1 - ptrStr; 
		   }
		   memset(timeBuff,0,64);
		   memcpy(typeBuff,ptrStr,lenTemp);		   
		   flag = 1;

		   if(strcmp(typeBuff,"wechat")==0)
		   {
		      paramResult->type = 1; 
		   }
		   else if(strcmp(typeBuff,"alipay")==0)
		   {
		      paramResult->type = 2; 
		   }
		   
	   }

	   ptrStr = strstr(ptrStr,"money");
	   if(ptrStr)
	   {
		   ptrStr+=6;//"money=xxx"
		   ptrTmp = strchr(ptrStr,',');
		   if(ptrTmp)
		   {
			  lenTemp =  ptrTmp - 1 - ptrStr;			  
		   }
		   else
		   {
			  lenTemp =  buff + buffLen -1 - ptrStr; 
		   }

		   paramResult->lenMoney = (unsigned short)lenTemp;
           memset(paramResult->money,0,32);
		   memcpy(paramResult->money,ptrStr,lenTemp);
		   flag = 1;		   
	   }
	   
	} 
}

void updateIp_MySql(int timeStamp,char * devId,unsigned int ipAddr,unsigned short port,int fd)
{
    char cmdStr[256];
	memset(cmdStr,0,256);
	struct in_addr addr;

	char ipPort[64] = {0};
	char * pIp = NULL;

	
	addr.s_addr = ipAddr;
	pIp=inet_ntoa(addr);
	sprintf(ipPort,"%s:%d:%d",pIp,port,fd);

	sprintf(cmdStr,"curl 127.0.0.1/tp5/?update=ip\\&time=%d\\&devId=%s\\&ip=%s",timeStamp,devId,ipPort);

	system(cmdStr);	
}


void updateStatus_MySql(char * devId, char * snapshot)
{
	char cmdStr[256];
	memset(cmdStr,0,256);

	sprintf(cmdStr,"curl 127.0.0.1/tp5/?update=status\\&devId=%s\\&snapshot=%s",devId,snapshot);
    //printf("%s\n",cmdStr);
	system(cmdStr); 
}

